package com.lirh.okhttp;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import sun.net.www.http.HttpClient;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class TestHttp {
 public  OkHttpClient httpClient;
    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36";

public TestHttp(){
    httpClient = new OkHttpClient();
}



    /**
     * get请求，参数一般都在url里
     */
    public  String sendGet(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    /**
     * post提交json
     *
     * @param url 地址
     * @param jsonStr json字符串
     */
    public  String sendPost(String url, String jsonStr) throws IOException {
        RequestBody body = RequestBody.create(JSON_TYPE, jsonStr);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    public static String testAnswer(String uuid,String question,String pid) throws IOException {

        String url = "*******";
        System.out.println(url);
        String jsonTemp="{\n" +
                "    \"senderId\":\"%s&%s\",\n" +
                "    \"asrConfidence\":1,\n" +
                "    \"productId\":\"%s\",\n" +
                "    \"query\":\"%s\",\n" +
                "    \"sessionId\":\"%s\",\n" +
                "    \"robotId\":\"%s\",\n" +
                "    \"message\":{\n" +
                "        \"relayNum\":\"\",\n" +
                "        \"phone\":\"1025\",\n" +
                "        \"phoneId\":\"\",\n" +
                "        \"callNum\":\"1025\",\n" +
                "        \"destNumber\":\"\",\n" +
                "        \"taskId\":\"\"\n" +
                "    }\n" +
                "}";
        String jsonStr = String.format(jsonTemp, 1125, uuid, pid,question, uuid,pid);
       // System.out.println(jsonStr);
        String s = new TestHttp().sendPost(url, jsonStr);
        // System.out.println(s);
        String msg="出错了";

        try {
            JSONObject json = JSONObject.parseObject(s);
            msg = json.getJSONObject("best").getJSONObject("reply").getString("voiceText");
        } catch (Exception e) {

        }
        return msg;

    }

}
